package service

import (
	"encoding/json"
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
)

func (s *ServiceSetup) SaveEdu(edu Education) (string, error) {
	eventID := "eventAddEdu"
	reg, notifier := registerEvent(s.Client, s.ChaincodeID, eventID) // 通知程序
	defer s.Client.UnregisterChaincodeEvent(reg)
	// 将edu对象序列化成为字节数组
	b, err := json.Marshal(edu)
	if err != nil {
		return "", fmt.Errorf("指定的edu对象序列化时发生错误")
	}
	req := channel.Request{
		ChaincodeID:     s.ChaincodeID,
		Fcn:             "addEdu",
		Args:            [][]byte{b, []byte(eventID)},
		TransientMap:    nil,
		InvocationChain: nil,
	}
	response, err := s.Client.Execute(req) //执行
	if err != nil {
		return "", err
	}
	err = eventResult(notifier, eventID)
	return string(response.TransactionID), nil
}
func (s *ServiceSetup) FindEduByCertNoAndName(certNo, name string) ([]byte, error) {
	req := channel.Request{
		ChaincodeID: s.ChaincodeID,
		Fcn:         "queryEduByCertNoAndName", // leveldb  can not rich query
		Args:        [][]byte{[]byte(certNo), []byte(name)},
	}
	response, err := s.Client.Query(req)
	if err != nil {
		return []byte{0x00}, err
	}
	return response.Payload, nil
}

func (s *ServiceSetup) FindEduInfoByEntityID(entityID string) ([]byte, error) {
	req := channel.Request{
		ChaincodeID:     s.ChaincodeID,
		Fcn:             "queryEduInfoByEntityID",
		Args:            [][]byte{[]byte(entityID)},
		TransientMap:    nil,
		InvocationChain: nil,
	}
	response, err := s.Client.Query(req)
	if err != nil {
		return []byte{0x00}, err
	}
	return response.Payload, nil
}

func (s *ServiceSetup) ModifyEdu(edu Education) (string, error) {
	eventID := "eventModifyEdu"
	reg, notifier := registerEvent(s.Client, s.ChaincodeID, eventID)
	defer s.Client.UnregisterChaincodeEvent(reg)
	// 将edu对象序列化成为字节数组
	b, err := json.Marshal(edu)
	if err != nil {
		return "", fmt.Errorf("指定的edu对象序列化时发生错误 : " + fmt.Sprintf("  \n %v ", err))
	}
	req := channel.Request{
		ChaincodeID:     s.ChaincodeID,
		Fcn:             "updateEdu",
		Args:            [][]byte{b, []byte(eventID)},
		TransientMap:    nil,
		InvocationChain: nil,
	}
	respone, err := s.Client.Execute(req)

	if err != nil {
		return "", err
	}

	err = eventResult(notifier, eventID)

	if err != nil {
		return "", err
	}

	return string(respone.TransactionID), nil
}
